import React, { Component } from 'react'
import {connect} from "react-redux"

import {increment,decrement,incrementAsync} from '../../redux/actions/count'

//定义UI组件
class Count extends Component {
  //因为UI组件是容器组件的子组件，所以父组件通过connect映射的状态和方法可以通过this.props拿到
  incrementCount=()=>{
    const {value}=this.selectNum
    this.props.increment(value*1)
  }
  decrementCount=()=>{
    const {value}=this.selectNum
    this.props.decrement(value*1)
  }
  incrementCountIfOdd=()=>{
    const {value}=this.selectNum
    if(this.props.count%2===0){
      this.props.increment(value*1)
    }
  }
  incrementCountAsync=()=>{
    const {value}=this.selectNum
    this.props.incrementAsync(value*1,1000)
  }
  render() {
    console.log('UI组件接收到容器组件的数据是',this.props);
    return (
      <div>
        <h1>当前求和为:{this.props.count}</h1>
        <h1>下方组件人数为:{this.props.person.length}</h1>
        <select ref={c=>this.selectNum=c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>&nbsp;
        <button onClick={this.incrementCount}>+</button>&nbsp;
        <button onClick={this.decrementCount}>-</button>&nbsp;
        <button onClick={this.incrementCountIfOdd}>偶数时再加</button>
        <button onClick={this.incrementCountAsync}>等待完再加</button>
      </div>
    )
  }
}
//暴露connect创建的包裹UI组件Count的容器组件
export default connect(
  //映射状态
  state=>({
    count:state.count,
    person:state.person
  }),
  //映射操作状态的方法，调用redux文件夹中action文件返回action对象，react-redux会自动分发dispatch给reducer改变状态
  {
    increment,
    decrement,
    incrementAsync
  }
)(Count)